<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <!-- 使用 el-row 和 el-col 实现两列布局 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入客户名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

<!--      <el-row :gutter="20">-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="联系电话" prop="contactPhone">-->
<!--            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->

<!--      <el-form-item label="企业工艺" prop="industryProcess">-->
<!--        <el-input-->
<!--          v-model="formData.industryProcess"-->
<!--          placeholder="请输入企业工艺"-->
<!--          type="textarea"-->
<!--          :maxlength="500"-->
<!--          :rows="3"-->
<!--          show-word-limit-->
<!--        />-->
<!--      </el-form-item>-->

<!--      <el-form-item label="企业产品" prop="products">-->
<!--        <el-input-->
<!--          v-model="formData.products"-->
<!--          :rows="3"-->
<!--          placeholder="请输入企业产品"-->
<!--          type="textarea"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-row :gutter="20">
        <el-col :span="24">
          <!-- 地址信息组合 -->
          <el-form-item label="所在地区" prop="areaIds" :rules="[{ required: true, message: '请选择所在地区', trigger: 'change' }]">
            <el-cascader
              v-model="formData.areaIds"
              :options="areaOptions"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children',
                checkStrictly: false,
                multiple: false,
                emitPath: true
              }"
              clearable
              placeholder="请选择所在地区"
              @change="handleAreaChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { CustomerApi, CustomerVO } from '@/api/dk/customer'
import { type AreaVO, getAreaTree } from '@/api/system/area' // 修改导入，添加类型导入
import { useCustomerStore } from '@/store/modules/customer/customer'
import { storeToRefs } from 'pinia'

/** 客户 表单 */
defineOptions({ name: 'CustomerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const customerStore = useCustomerStore()
const { areaOptions } = storeToRefs(customerStore)

// 修改表单数据结构，添加省市区字段
const formData = ref<{
  id?: number
  name?: string
  employeeCount?: string | number
  companyType?: string
  contactPerson?: string
  industryProcess?: string
  contactPhone?: string
  areaIds: number[]
  province?: string
  city?: string
  district?: string
  products?: string
  address?: string
}>({
  id: undefined,
  name: undefined,
  employeeCount: undefined,
  companyType: undefined,
  contactPerson: undefined,
  industryProcess: undefined,
  contactPhone: undefined,
  areaIds: [], // 用于级联选择器
  province: undefined, // 省份ID
  city: undefined, // 城市ID
  district: undefined, // 区县ID
  products: undefined,
  address: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  employeeCount: [
    { required: true, message: '企业人数不能为空', trigger: 'blur' },
    // 添加正数验证
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && (!Number(value) || Number(value) <= 0)) {
          callback(new Error('企业人数必须为正数'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  contactPerson: [
    { required: true, message: '联系人不能为空', trigger: 'blur' },
    // 添加长度限制
    { max: 4, message: '联系人不能超过4个字符', trigger: 'blur' }
  ],
  // industryProcess: [{ required: true, message: '企业工艺不能为空', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    // 添加手机号码验证
    {
      validator: (rule: any, value: any, callback: any) => {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  areaIds: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  // products: [{ required: true, message: '企业产品不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  formType.value = type
  resetForm()
  formLoading.value = true

  try {
    // 确保地区数据已加载
    await customerStore.loadAreaData()

    // 修改时，加载客户数据
    if (id) {
      const customerData = await CustomerApi.getCustomer(id)
      // 处理地区数据
      if (customerData.province) {
        const areaIds: number[] = []
        if (customerData.province) areaIds.push(Number(customerData.province))
        if (customerData.city) areaIds.push(Number(customerData.city))
        if (customerData.district) areaIds.push(Number(customerData.district))
        customerData.areaIds = areaIds
      }
      formData.value = {
        ...customerData,
        province: customerData.province?.toString(),
        city: customerData.city?.toString(),
        district: customerData.district?.toString()
      }
    }

    // 所有数据加载完成后再显示弹窗
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerVO
    if (formType.value === 'create') {
      await CustomerApi.createCustomer(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerApi.updateCustomer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 处理地区选择变化 */
const handleAreaChange = (value: number[]) => {
  console.log('选择的地区值:', value)
  if (!value || value.length === 0) {
    formData.value.areaIds = []
    formData.value.province = undefined
    formData.value.city = undefined
    formData.value.district = undefined
    return
  }

  // 更新 areaIds 和对应的省市区字段
  formData.value.areaIds = value
  formData.value.province = value[0]?.toString() || undefined
  formData.value.city = value[1]?.toString() || undefined
  formData.value.district = value[2]?.toString() || undefined
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    employeeCount: undefined,
    companyType: undefined,
    contactPerson: undefined,
    industryProcess: undefined,
    contactPhone: undefined,
    areaIds: [],
    province: undefined,
    city: undefined,
    district: undefined,
    products: undefined,
    address: undefined
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.el-cascader {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: Arial, sans-serif;
  line-height: 1.5;
}

/* 调整表单布局 */
:deep(.el-form-item) {
  margin-bottom: 22px;
}

/* 调整弹窗内容区域的内边距 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

/* 调整级联选择器宽度 */
:deep(.el-cascader) {
  width: 100%;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

/* 确保输入框和级联选择器高度一致 */
:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}
</style>
